package com.example.springbootpro.config;

import com.example.springbootpro.exception.BusinessException;
import com.example.springbootpro.util.JWTUtils;
import com.example.springbootpro.util.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.catalina.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;

public class JWTInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(JWTInterceptor.class);

    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/static/", "/resources/", "/public/", "/css/", "/js/", "/images/",
            "/favicon.ico", "/**.html", "/**.css", "/**.js", "/**.jpg", "/**.png"
    );
    /**
     * 记录请求详细信息
     */
    private void logRequestInfo(HttpServletRequest request) {
        if (logger.isDebugEnabled()) {
            logger.debug("====== 请求信息开始 ======");
            logger.debug("请求方法: {}", request.getMethod());
            logger.debug("请求URI: {}", request.getRequestURI());
            logger.debug("客户端IP: {}", request.getRemoteAddr());
            logger.debug("请求协议: {}", request.getProtocol());

            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                logger.debug("请求头 {}: {}", headerName, request.getHeader(headerName));
            }

            logger.debug("====== 请求信息结束 ======");
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         if (isStaticResource(request.getRequestURI()))
        {
            return  true;
        }
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")||token.strip().equals("")) {
            throw new BusinessException("401", "请先登录");
        }
        try {
            JWTUtils.verifyToken(token.replace("Bearer","").strip());
            String username = JWTUtils.getUsernameFromToken(token.replace("Bearer", "").strip());
            UserContext.setCurrentUser(username);
            return true;
        } catch (Exception e) {
            throw new BusinessException("401", "验证失败+" + e.getMessage());
        }
    }

    private boolean isStaticResource(String uri) {
        return EXCLUDE_PATHS.stream().anyMatch(uri::startsWith) ||
                uri.matches(".*\\.(css|js|png|jpg|jpeg|gif|ico|woff|woff2|ttf|map|mp4|webm)$");
    }
}